#include <fstream>
#include <iostream>
#include <string>

#include <cv.h>
#include <highgui.h>

namespace MNIST
{
	int reverseInt(int i) 
	{
		unsigned char c1, c2, c3, c4;
		c1 = i & 255;
		c2 = (i >> 8) & 255;
		c3 = (i >> 16) & 255;
		c4 = (i >> 24) & 255;
		return ((int)c1 << 24) + ((int)c2 << 16) + ((int)c3 << 8) + c4;
	}

	void create_image(unsigned char* data)
	{
		string imgname;
		ostringstream imgstrm;
		string fullpath;

		fullpath = "c:\\MNIST\\1.bmp";

		CvSize size;
		size.height = 29;
		size.width = 29;
		IplImage *img = cvCreateImage(size, IPL_DEPTH_8U, 1);


		img->imageData = (char*)data;

		cvSaveImage(fullpath.c_str(), img);

	}

	void ReadImage(string str, vector<vector<int>> &vec)
	{
		ifstream file(str.c_str(), ios::binary);
		if(file.is_open())
		{
			cout << "success to load the file" << endl; 

			int magic_number = 0;
			int number_of_images = 0;
			int n_rows;
			int n_cols;
			unsigned char temp = 0;

			file.read((char*)&magic_number, sizeof(magic_number));
			magic_number = reverseInt(magic_number);
			cout << magic_number  << endl;

			file.read((char*)&number_of_images,sizeof(number_of_images));
			number_of_images = reverseInt(number_of_images);
			cout << number_of_images << endl;

			file.read((char*)&n_rows,sizeof(n_rows));
			n_rows = reverseInt(n_rows);
			cout << n_rows << endl;

			file.read((char*)&n_cols,sizeof(n_cols));
			n_cols = reverseInt(n_cols);
			cout << n_cols << endl;
			
			for(int i = 0; i < number_of_images; ++i)
			{
				vector<int> dVec;
				dVec.clear();
				for(int r = 0; r < n_rows; ++r)
				{
					for(int c = 0; c < n_cols; ++c)
					{
						file.read((char*)&temp, sizeof(temp));
						dVec.push_back((int)temp);
					}
				}
				vec.push_back(dVec);
			}

		}else
		{
			cout << "fail to load the file" << endl;
		}
	}

	void ReadLabel(string str, vector<int> &vec)
	{
		ifstream file(str.c_str(), ios::binary);
		if(file.is_open())
		{
			cout << "success to load the file" << endl; 

			int magic_number = 0;
			int number_of_images = 0;
			unsigned char temp = 0;

			file.read((char*)&magic_number, sizeof(magic_number));
			magic_number = reverseInt(magic_number);
			cout << magic_number  << endl;

			file.read((char*)&number_of_images,sizeof(number_of_images));
			number_of_images = reverseInt(number_of_images);
			cout << number_of_images << endl;
			
			for(int i = 0; i < number_of_images; ++i)
			{
				file.read((char*)&temp, sizeof(temp));
				vec.push_back((int)temp);
			}

		}else
		{
			cout << "fail to load the file" << endl;
		}
	}
}
